// pages/component/sharespace/sharespace.js
var Api = require("../../common/api/api.js")
var App = getApp();
var loadMoreView, page
const http = require('../../utils/http')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    current: 0,
    currentType: 1, //当前选择的类型


    feed: [],
    feed_length: 0,
    userId: 0, //当前用户ID

    // banner轮播组件属性
    indicatorDots: true, // 是否显示面板指示点	
    autoplay: true, // 是否自动切换
    interval: 3000, // 自动切换时间间隔
    duration: 800, // 滑动动画时长
    scrollTop: 0,
    pageCarousels: {}, //图片轮播

    system: {}, //系统信息
    items: [],
    resultData: [], // 存放数据
    spaceMembers: [], //所有成员
    selectedView: 'article',
    page: 0,

    id: 0,  //圈子主键ID

    //点赞按钮
    thumbUpButtonFalse: "../../../image/icon/dianzan.png",
    thumbUpButtonTrue: "../../../image/icon/dianzan_default.png",


    //------- 圈子信息 --------
    briefIntroduction: "", //空间简介 ,
    buttonChange: false, //true：立即加入；false：发布动态（表示已加入该空间） ,
    day: 0, //创建天数 ,
    imgName: "", //空间展示图（名称） ,
    name: "", // 空间名称,
    nickname: "", //圈主昵称,
    headImg: "", //圈主头像
    masterOpenid: "", //圈主openid

    openid: "", //当前登录用户openid
  },


  onClickItem(e) {
    let idx = e.currentTarget.dataset.idx;
    this.setData({
      currentType: parseInt(idx) + 1,
    });
    page = 0;
    loadMoreView = this.selectComponent("#loadMoreView");
    this.loadData('article', true, parseInt(idx) + 1);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getSpaceInfo(options.id);

    this.setData({
      id: options.id,
      openid: wx.getStorageSync("openid"),
    })
    page = 0;
    loadMoreView = this.selectComponent("#loadMoreView");
    this.loadData('article', true, 1);
  },


  loadData: function (viewType, showLoading, type) {
    /**
     * id (integer, optional): 空间ID ,
     * type (integer, optional): 类型；1：阅读；2：商品；3：直播；4：成员
     */

    var that = this;
    http.post({
      url: Api.host + '/api/topics/getTopics',
      data: {
        id: that.data.id,
        // id: 1,
        page: page,
        limit: 10,
        type: type,
        openid: wx.getStorageSync("openid"),
      },
      showLoading: showLoading,
      success: (res) => {
        var items = that.data.resultData;
        if (page == 0) {
          items = res.topicsInfos;
          wx.stopPullDownRefresh()
        } else {
          items = items.concat(res.topicsInfos);
        }
        that.setData({
          items: items,
          resultData: items,
          selectedView: viewType,
          spaceMembers: res.spaceMembers,
        })

        loadMoreView.loadMoreComplete(res.topicsInfos)
      },
      fail: () => {
        if (page != 0) {
          loadMoreView.loadMoreFail()
        }
      }
    })
  },
  loadMoreListener: function (e) {
    page += 1
    this.loadData(this.data.selectedView, false, 1)
  },
  clickLoadMore: function (e) {
    this.loadData(this.data.selectedView, false, 1)
  },



  /**
  * 页面相关事件处理函数--监听用户下拉动作
  */
  onPullDownRefresh: function () {
    page = 0
    this.loadData(this.data.selectedView, false, 1)
  },

  /**
     * 页面上拉触底事件的处理函数
     */
  onReachBottom: function () {
    loadMoreView.loadMore()
  },

  onPageScroll: function (e) {
    console.log(e)
    if (e.scrollTop >= this.data.system.windowWidth / 9 * 5 && !this.data.float) {
      this.setData({
        float: true
      })
    } else if (e.scrollTop < this.data.system.windowWidth / 9 * 5 && this.data.float) {
      this.setData({
        float: false
      })
    }
  },

  /**
   * 获取圈主及空间信息
   */
  getSpaceInfo: function (id) {
    let _this = this;

    //请求参数封装
    var data = {
      id: id,
      openid: wx.getStorageSync('openid'),
    }
    var params = JSON.stringify(data)

    Api.getSpaceInfo(params).then(function (result) {
      _this.setData({
        briefIntroduction: result.data.data.briefIntroduction,
        buttonChange: result.data.data.buttonChange,
        day: result.data.data.day,
        imgName: result.data.data.imgName,
        name: result.data.data.name,
        nickname: result.data.data.nickname,
        headImg: result.data.data.headImg,
        masterOpenid: result.data.data.openid,
      });
    }).catch(function (error) {
      console.log(error)
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 成员删除
   */
  del: function (e) {
    let _this = this;

    //圈子成员 id
    let id = e.currentTarget.dataset.id;

    wx.showModal({
      // title: '确定',
      content: '是否已确认删除该成员？',
      success(res) {
        if (res.confirm) {
          //请求参数封装
          var data = {
            id: id,
            openid: wx.getStorageSync('openid'),
          }
          var params = JSON.stringify(data)

          Api.delMember(params).then(function (result) {
            App.showSuccess("操作成功");
            page = 0
            _this.loadData(_this.data.selectedView, false, 4)
          }).catch(function (error) {
            console.log(error)
          })

        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    });
  },


  /**
   * 立即加入圈子
   */
  join: function () {
    let _this = this;

    //请求参数封装
    var data = {
      id: _this.data.id,
      openid: wx.getStorageSync('openid'),
    }
    var params = JSON.stringify(data)

    Api.joinSpace(params).then(function (result) {
      App.showSuccess("成功发起申请");
      _this.getSpaceInfo(_this.data.id)
    }).catch(function (error) {
      console.log(error)
    })

  },

  toPubulishTopic:function(){
    wx.navigateTo({
      url: '../publishtopic/publishtopic?id='+this.data.id+'&type='+this.data.currentType,
    })
  },


  //同意加入
  agree: function(e){
    let _this = this;
    //请求参数封装
    var data = {
      id: e.target.dataset.id,
      type: 1
    }
    var params = JSON.stringify(data)

    Api.memberOperation(params).then(function (result) {
      page = 0
      _this.loadData(_this.data.selectedView, false, 4)
    }).catch(function (error) {
      console.log(error)
    })
  },


  //拒绝加入
  refuse: function (e) {
    let _this = this;

    wx.showModal({
      // title: '确定',
      content: '是否已确认拒绝该成员的加入？',
      success(res) {
        if (res.confirm) {
          //请求参数封装
          var data = {
            id: e.target.dataset.id,
            type: 2
          }
          var params = JSON.stringify(data)

          Api.memberOperation(params).then(function (result) {
            page = 0
            _this.loadData(_this.data.selectedView, false, 4)
          }).catch(function (error) {
            console.log(error)
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    });
  }



})